﻿using System;
using System.Linq;
using System.Text;
using BestEasyCMS.Framework.Extension;
using BestEasyCMS.Framework.Querying;
using BestEasyCMS.Framework.UnitOfWork;
using BestEasyCMS.Model.IRepository.Security;
using BestEasyCMS.Model.Security;
using BestEasyCMS.Service.Interfaces.Security;
using BestEasyCMS.Service.Mappers;
using BestEasyCMS.Service.Messages;
using BestEasyCMS.Service.Messages.Security.Request;
using BestEasyCMS.Service.Messages.Security.Response;
using BestEasyCMS.Service.Views.Security;


namespace BestEasyCMS.Service.Impl.Security.Users
{
    public class UserService : IUserService
    {
        private readonly IUserRepository _userRepository;
        private readonly IUnitOfWork _uow;

        public UserService(IUserRepository userRepository, IUnitOfWork uow)
        {
            _userRepository = userRepository;
            _uow = uow;
        }

        public FindResponse<UserView> FindBy(long id)
        {
            var response = new FindResponse<UserView>();
            var result = _userRepository.FindBy(id);
            if (result == null)
            {
                response.IsSuccess = false;
                response.Message = "无相关数据！";
                return response;
            }
            response.IsSuccess = true;
            response.Message = "获取成功！";
            response.View = Convert<UserView, User>.ToView(result);
            return response;
        }

        public ResponseBase Update(UserView view)
        {
            var response = new ResponseBase();
            try
            {
                var entity = Convert<UserView, User>.ToEntity(view);
                ThrowExceptionIfUserIsInvalid(entity);
                _userRepository.Update(entity);
                _uow.Commit();
                response.IsSuccess = true;
                response.Message = "保存成功！";
            }
            catch (Exception ex)
            {
                response.IsSuccess = false;
                response.Message = ex.Message;
            }
            return response;
        }

        public LoginResponse Login(LoginRequest request)
        {
            var response = new LoginResponse();
            //var query = new Query();
            //query.Add(Criterion.Create<User>(p => p.LoginName, request.LoginName, CriteriaOperator.Equal));
            //var user = _userRepository.FindBy(query).SingleOrDefault();
            var user =
                _userRepository.Query()
                    .Include(p => p.Role)
                    .Where(p => p.LoginName == request.LoginName)
                    .ToEnumerable()
                    .SingleOrDefault();
            response.IsSuccess = false;
            if (user == null)
            {
                response.State = UserState.DoNotExist;
                response.Message = "用户不存在！";
                return response;
            }
            if (user.IsDel == true && user.IsEnable == false)
            {
                response.State = UserState.Disable;
                response.Message = "用户冻结或删除，请联系网站管理员！";
                return response;
            }
            if (!user.Password.Equals(request.Password))
            {
                response.State = UserState.UsernameOrPasswordIsWrong;
                response.Message = "用户名或密码错误！";
                return response;
            }
            response.IsSuccess = true;
            response.Message = "验证通过！";
            response.View = Convert<UserView, User>.ToView(user);
            return response;
        }

        public ResponseBase Register(RegisterUserRequest request)
        {
            var response = new ResponseBase();
            try
            {
                var entity = Convert<UserView, User>.ToEntity(request.UserView);
                ThrowExceptionIfUserIsInvalid(entity);
                _userRepository.Insert(entity);
                _uow.Commit();
                response.IsSuccess = true;
                response.Message = "保存成功！";
            }
            catch (Exception ex)
            {
                response.IsSuccess = false;
                response.Message = ex.Message;
            }
            return response;
        }

        public FindPageResponse<UserView> FindPageBy(GetUserPageRequest request)
        {
            var response = new FindPageResponse<UserView>();

            var results = _userRepository.Query()
                .Include(p => p.Role)
                .HasWhere(request.LoginName, p => p.LoginName.Contains(request.LoginName))
                .HasWhere(request.RoleId, p => p.RoleId == request.RoleId)
                .HasWhere(request.IsEnable, p => p.IsEnable == request.IsEnable)
                .ToPage(request.Paged.PageIndex, request.Paged.PageSize);

            if (!results.Items.Any())
            {
                response.IsSuccess = false;
                response.Message = "暂无相关数据！";
                return response;
            }
            response.IsSuccess = true;
            response.Message = "获取成功！";
            response.Page = results.ToPageView<UserView, User>();
            return response;
        }

        #region Private Method
        /// <summary>
        /// 如果User无效，则引发异常
        /// </summary>
        /// <param name="user"></param>
        private void ThrowExceptionIfUserIsInvalid(User user)
        {
            if (user.GetBrokenRules().ToList().Count > 0)
            {
                var brokenRules = new StringBuilder();
                brokenRules.AppendLine("错误信息：");
                foreach (var businessRule in user.GetBrokenRules())
                {
                    brokenRules.AppendLine(businessRule.Rule);
                }
                throw new UserInvalidException(brokenRules.ToStr());
            }
        }
        #endregion
    }
}
